import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Route, routes } from '.'

export const RouterBeforeEach = ({ children }: any) => {
  const location = useLocation()
  const navigate = useNavigate()

  useEffect(() => {
    const getCurrentRouterMap = (routes: any[], path: string): Route => {
      for (let route of routes) {
        if (route.path === path) return route
        if (route.children) {
          const childRouter = getCurrentRouterMap(route.children, path)
          if (childRouter) return childRouter
        }
      }
      return routes[routes.length - 1]
    }
    let router = getCurrentRouterMap(routes, location.pathname)
    let token = sessionStorage.getItem('token')
    if (!token) {
      if (router.auth) {
        localStorage.setItem('key', location.search)
        navigate(`/login${location.search}`, { replace: true })
      }
    }
  }, [location.pathname, location.search, navigate])
  return children
}
